# -*- coding:utf-8 -*-
from __future__ import print_function

import os

import shutil

'''
广目IoT平台1vn人脸识别
@File : GMIoT.py

@Author: 爸爸

@Date : 2019/4/4

@Desc :
url: http://test.gmp.gmface.tech/
username :  test@tongfang.tech
pwd: tongfangweishi123456
'''
import hashlib
import json
import random
import time

import requests

APP_id = "tf_test"
APP_secret = "tongfang_secret"
BaseUrl = "http://test.gmp-api.gmface.tech/"
err_code = {
    10050: "参数为空",
    10061: "时间错误",
    10062: "噪声字符串错误",
    10063: "appid不存在",
    10064: "签名错误",
    19999: "未知错误",
    30500: "计算图片特征失败",
    30501: "拷贝图片文件失败",
    30502: "添加图片模型失败",
    30503: "保存图片识别",

}


# 获取sign
def get_sign(datadict):
    d = sorted(datadict.items())
    d_str = ""
    for k, v in d:
        d_str += "{}={}&".format(k, v)
    d_str = d_str.strip("&") + APP_secret
    # print d_str
    md5 = hashlib.md5(d_str.encode("utf-8"))
    res = md5.hexdigest().upper()
    # print res
    return res


# 获取时间戳
def get_timestamp():
    return int(time.time())


# 获取16位随机字符串
def get_noise_str():
    cs = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890")
    random.shuffle(cs)
    return "".join(cs[:16])


class GMIot(object):
    def __init__(self, baseurl):
        self.base_url = baseurl

    def __get(self, url, data):
        r = requests.get(url, params=data)
        if r.ok:
            return r.content
        else:
            return "get error,status_code:%d" % r.status_code

    def __post(self, url, data):
        r = requests.post(url, data)
        if r.ok:
            return r.content
        else:
            return "post error,status_code:%d" % r.status_code

    def __postFile(self, url, data, files):
        r = requests.post(url, data=data, files=files)
        if r.ok:
            return r.content
        else:
            return "postfile error,status_code:%d" % r.status_code

    def __put(self, url, data):
        r = requests.put(url, data)
        if r.ok:
            return r.content
        else:
            return "put error,status_code:%d" % r.status_code

    def __delete(self, url, data):
        r = requests.delete(url, params=data)
        if r.ok:
            return r.content
        else:
            return "delete error,status_code:%d" % r.status_code

    def __signData(self, data):
        timestamp = get_timestamp()
        noisestr = get_noise_str()
        res = {
            "timestamp": timestamp,
            "noise_str": noisestr,
            "app_id": APP_id,
        }
        res.update(data)
        sign = get_sign(res)
        res["sign"] = sign
        return res

    def debugSign(self):
        url = self.base_url + "api/debug/signature"
        data = {
            "user_id": "测试用户",
            "extra_param": 123
        }
        data = self.__signData(data)
        print(data)
        res = self.__post(url, data)
        print(res)

    def flush(self):
        url = self.base_url + "api/debug/flushflag"
        data = {}
        data = self.__signData(data)
        res = self.__get(url, data)
        print(res)

    def getPersonList(self, page=1, page_size=15, person_name="", group_id=0):
        url = self.base_url + "external/person/list"
        data = {
            "page": page,
            "page_size": page_size,
            "person_name": person_name,
            "group_id": group_id
        }
        data = self.__signData(data)
        res = self.__get(url, data)
        print(res)

    def addPerson(self, filepath, person_name, person_group_id_list=[], person_external_id="", person_type=1):
        # person_group_id_list 是数组格式的字符串
        imginfo = self.uplode(filepath)
        img = json.loads(imginfo)
        if len(img["data"])<=0:
            return ""
        imgid = int(img["data"]["image_id"])
        url = self.base_url + "external/person/add"
        data = {
            "image_id": imgid,
            "person_name": person_name,
            "person_group_id_list": "{}".format(person_group_id_list),
            "person_external_id": person_external_id,
            "person_type": person_type,
        }
        data = self.__signData(data)
        print(data)
        res = self.__post(url, data)
        print(res)

    def delPerson(self, person_id):
        url = self.base_url + "external/person/{}/delete".format(person_id)
        data = {}
        data = self.__signData(data)
        res = self.__delete(url, data)
        print(res)

    def editPerson(self, person_id, person_name, image_id, person_group_id_list=[], person_external_id="",
                   person_type=1):
        url = self.base_url + "external/person/{}/edit".format(person_id)
        data = {
            "image_id": image_id,
            "person_name": person_name,
            "person_group_id_list": "{}".format(person_group_id_list),
            "person_external_id": person_external_id,
            "person_type": person_type,
        }
        data = self.__signData(data)
        res = self.__put(url, data)
        print(res)

    def getGroupAll(self, page=0, page_size=15, group_name="", group_remark=""):
        data = {}
        if page == 0:
            url = self.base_url + "external/group/list/all"
        else:
            url = self.base_url + "/external/group/list"
            data["page"] = page
            data["page_size"] = page_size
            data["group_name"] = group_name
            data["group_remark"] = group_remark
        data = self.__signData(data)
        res = self.__get(url, data)
        print(res)

    def addGroup(self, group_name, group_remark=""):
        # 无group_area_id_list参数
        url = self.base_url + "external/group/add"
        data = {
            "group_name": group_name,
            "group_remark": group_remark
        }
        data = self.__signData(data)
        print(data)
        res = self.__post(url, data)
        print(res)

    def uplode(self, filepath):
        url = self.base_url + "external/image/upload"
        data = {}
        data = self.__signData(data)
        # print (data)
        res = self.__postFile(url, data, files={"file": open(filepath, "rb")})
        return res

    def recognition(self, filepath, group_id=1, max_faces=1):
        url = self.base_url + "external/analyse/recognition"
        data = {
            "group_id": group_id,
            "max_faces": max_faces
        }
        data = self.__signData(data)
        # print(data)
        res = self.__postFile(url, data, files={"file": open(filepath, "rb")})
        # print(res)
        return res

    def test(self):
        dirpath=".\\img"
        bakpath=".\\bak"
        tarpath='.\\Face\\xjc'
        videopath=".\\VideoImage"
        # self.flush()
        lists = os.listdir(tarpath)
        imglist = [i for i in lists if i.endswith(".jpg")]
        for img in imglist:
        #     times=time.time()*1000
        #     res=self.recognition(filepath=f"{tarpath}\\{img}", group_id=8)
        #     res=json.loads(res)
        #     timee=time.time()*1000
        #     if res["code"]==0:
        #         isInsert=False
        #         for i in res["data"]["result"]["faces"]:
        #             print(img, i["person_id"],i["result"], i["score"],timee-times)
        #             if float(i["score"])<85.0: #不是同一个人需要插入
        #                 isInsert = isInsert or True
        #             elif float(i["score"])>=85.0 and i["result"]==1:
        #                 isInsert = isInsert and False
        #         if len(res["data"]["result"]["faces"])==0:
        #             print (img,timee-times)
        #         if isInsert:
        #             pass
        #             # tempname=int(time.time())
        #             # self.addPerson(filepath=f"{dirpath}\\{img}",person_name=f"temp{tempname}",person_group_id_list=[8],person_external_id=f"temp{tempname}") #groupid 应与目标群组id一致
        #             # self.flush()
        #     # shutil.move(f"{dirpath}\\{img}", f"{bakpath}\\{img}")
        #
        # # self.flush()
        # # self.getGroupAll()
        # # self.addGroup("test_4_18_1606", "test4181606")
        # # self.recognition(filepath="./img/testxy.jpg", group_id=8, max_faces=3)
        # # self.debugSign()
        # # self.uplode("./img/jobs.jpg")
        # # self.getPersonList(group_id=8,person_name="马")
        # # self.addPerson("./img/yl.jpg", "银临", person_group_id_list=[8])
        # # self.delPerson(11)
        # # self.editPerson(13,image_id=13, person_name="马云", person_group_id_list=[8],person_external_id="马云")
        # # timeend = time.time() * 1000
        # # print(timeend - timestart)
            tempname = time.time()*1000
            self.addPerson(filepath=f"{tarpath}\\{img}", person_name=f"temp{tempname}", person_group_id_list=[8],
                           person_external_id=f"temp{tempname}")  # groupid 应与目标群组id一致




def main():
    gmiot = GMIot(BaseUrl)
    gmiot.test()


if __name__ == '__main__':
    main()
